package com.sunday.gateway.study.circuit.breaker;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.LocalDateTime;

@Slf4j
@Service
public class MyService {

    private final ReactiveCircuitBreaker myCircuitBreaker;

    public MyService(ReactiveCircuitBreakerFactory circuitBreakerFactory) {
        this.myCircuitBreaker = circuitBreakerFactory.create("myExampleBreaker");
        log.info("{}", myCircuitBreaker);
    }

    public Mono<String> process(long seconds) {

        log.info("请求开始");

        Mono<String> delayedMono = Mono.delay(Duration.ofSeconds(seconds)).thenReturn("Delayed result");

//        Mono<String> result = Mono.just("Hello, Circuit Breaker!");

        return myCircuitBreaker.run(delayedMono,
                throwable -> Mono.just(STR."Fallback! \{LocalDateTime.now()} === \{throwable.toString()}"));
    }

}
